<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4CAF50',
                        secondary: '#FFC107',
                        dark: '#212121',
                        light: '#F5F5F5'
                    },
                    fontFamily: {
                        game: ['"Press Start 2P"', 'cursive', 'system-ui']
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .pixel-corners {
                clip-path: polygon(
                    0% 4px, 4px 4px, 4px 0%, calc(100% - 4px) 0%, calc(100% - 4px) 4px, 100% 4px,
                    100% calc(100% - 4px), calc(100% - 4px) calc(100% - 4px), calc(100% - 4px) 100%,
                    4px 100%, 4px calc(100% - 4px), 0% calc(100% - 4px)
                );
            }
            .game-shadow {
                box-shadow: 0 0 0 4px #212121, 0 0 0 8px #424242;
            }
        }
    </style>
    <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap" rel="stylesheet">
</head>
<body class="bg-gray-900 min-h-screen flex flex-col items-center justify-center p-4 text-light font-game">
    <div class="w-full max-w-2xl">
        <header class="text-center mb-8">
            <h1 class="text-[clamp(1.5rem,5vw,3rem)] font-bold text-primary mb-2 tracking-wider">贪吃蛇</h1>
            <p class="text-gray-400 text-sm md:text-base">使用方向键或WASD控制蛇的移动</p>
        </header>

        <main class="bg-dark rounded-lg pixel-corners game-shadow p-4 md:p-6">
            <div class="flex flex-col md:flex-row gap-4">
                <div class="flex-1 flex flex-col">
                    <div class="relative bg-gray-800 rounded pixel-corners overflow-hidden" style="aspect-ratio: 1/1;">
                        <canvas id="gameCanvas" class="w-full h-full"></canvas>
                        
                        <!-- 游戏开始遮罩 -->
                        <div id="startScreen" class="absolute inset-0 bg-dark/80 flex flex-col items-center justify-center z-10">
                            <button id="startButton" class="bg-primary hover:bg-primary/80 text-white font-bold py-3 px-6 rounded pixel-corners transition-all duration-200 transform hover:scale-105">
                                <i class="fa fa-play mr-2"></i>开始游戏
                            </button>
                            <p class="mt-4 text-gray-300 text-center px-4">收集食物使蛇变长<br>不要撞到墙壁或自己的身体</p>
                        </div>
                        
                        <!-- 游戏结束遮罩 -->
                        <div id="gameOverScreen" class="absolute inset-0 bg-dark/80 flex flex-col items-center justify-center z-10 hidden">
                            <h2 class="text-secondary text-2xl mb-2">游戏结束!</h2>
                            <p class="text-gray-300 mb-4">得分: <span id="finalScore" class="text-white">0</span></p>
                            <button id="restartButton" class="bg-primary hover:bg-primary/80 text-white font-bold py-3 px-6 rounded pixel-corners transition-all duration-200 transform hover:scale-105">
                                <i class="fa fa-refresh mr-2"></i>再玩一次
                            </button>
                        </div>
                    </div>
                    
                    <div class="mt-4 grid grid-cols-2 gap-2">
                        <div class="bg-gray-800 rounded pixel-corners p-3">
                            <div class="flex items-center justify-between">
                                <span class="text-gray-400 text-sm">当前得分</span>
                                <span id="score" class="text-white text-lg">0</span>
                            </div>
                        </div>
                        <div class="bg-gray-800 rounded pixel-corners p-3">
                            <div class="flex items-center justify-between">
                                <span class="text-gray-400 text-sm">最高分</span>
                                <span id="highScore" class="text-white text-lg">0</span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="w-full md:w-64 space-y-4">
                    <div class="bg-gray-800 rounded pixel-corners p-4">
                        <h3 class="text-secondary text-center mb-3">游戏控制</h3>
                        <!-- 修复：重新设计方向按钮的网格布局 -->
                        <div class="grid grid-cols-3 gap-2 text-center justify-items-center">
                            <div class="col-span-3">
                                <button class="direction-btn bg-gray-700 hover:bg-gray-600 text-white w-10 h-10 rounded flex items-center justify-center transition-colors" data-direction="up">
                                    <i class="fa fa-chevron-up"></i>
                                </button>
                            </div>
                            <div>
                                <button class="direction-btn bg-gray-700 hover:bg-gray-600 text-white w-10 h-10 rounded flex items-center justify-center transition-colors" data-direction="left">
                                    <i class="fa fa-chevron-left"></i>
                                </button>
                            </div>
                            <div>
                                <button class="direction-btn bg-gray-700 hover:bg-gray-600 text-white w-10 h-10 rounded flex items-center justify-center transition-colors" data-direction="down">
                                    <i class="fa fa-chevron-down"></i>
                                </button>
                            </div>
                            <div>
                                <button class="direction-btn bg-gray-700 hover:bg-gray-600 text-white w-10 h-10 rounded flex items-center justify-center transition-colors" data-direction="right">
                                    <i class="fa fa-chevron-right"></i>
                                </button>
                            </div>
                        </div>
                        <div class="mt-3 text-xs text-gray-400 text-center">
                            <p>或使用键盘WASD</p>
                        </div>
                    </div>
                    
                    <div class="bg-gray-800 rounded pixel-corners p-4">
                        <h3 class="text-secondary text-center mb-3">游戏设置</h3>
                        <div class="space-y-3">
                            <div>
                                <label class="block text-gray-300 text-xs mb-1">游戏速度</label>
                                <input type="range" id="speedSlider" min="1" max="8" value="4" class="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer accent-primary">
                                <div class="flex justify-between text-xs text-gray-400">
                                    <span>慢</span>
                                    <span id="speedValue">4</span>
                                    <span>快</span>
                                </div>
                            </div>
                            
                            <button id="pauseButton" class="w-full bg-gray-700 hover:bg-gray-600 text-white py-2 rounded pixel-corners transition-colors flex items-center justify-center">
                                <i class="fa fa-pause mr-2"></i>暂停游戏
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </main>
        
        <footer class="mt-8 text-center text-gray-500 text-xs">
            <p>使用HTML5 Canvas和Tailwind CSS v3构建</p>
        </footer>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // 游戏常量和变量
            const canvas = document.getElementById('gameCanvas');
            const ctx = canvas.getContext('2d');
            const startScreen = document.getElementById('startScreen');
            const gameOverScreen = document.getElementById('gameOverScreen');
            const finalScore = document.getElementById('finalScore');
            const scoreDisplay = document.getElementById('score');
            const highScoreDisplay = document.getElementById('highScore');
            const startButton = document.getElementById('startButton');
            const restartButton = document.getElementById('restartButton');
            const pauseButton = document.getElementById('pauseButton');
            const speedSlider = document.getElementById('speedSlider');
            const speedValue = document.getElementById('speedValue');
            const directionButtons = document.querySelectorAll('.direction-btn');
            
            // 设置Canvas尺寸
            const gridSize = 20;
            const calculateCanvasSize = () => {
                const container = canvas.parentElement;
                const size = Math.min(container.clientWidth, container.clientHeight);
                const gridCount = 20; // 20x20网格
                const cellSize = Math.floor(size / gridCount);
                canvas.width = gridCount * cellSize;
                canvas.height = gridCount * cellSize;
                return { cellSize, gridCount };
            };
            
            let { cellSize, gridCount } = calculateCanvasSize();
            
            // 响应式调整
            window.addEventListener('resize', () => {
                const newSize = calculateCanvasSize();
                cellSize = newSize.cellSize;
                gridCount = newSize.gridCount;
                if (gameState === 'running') {
                    draw();
                }
            });
            
            // 游戏状态
            let snake = [];
            let food = {};
            let direction = 'right';
            let nextDirection = 'right';
            let score = 0;
            let highScore = localStorage.getItem('snakeHighScore') || 0;
            let gameState = 'ready'; // ready, running, paused, gameOver
            let gameLoop;
            let speed = 4;
            let speedInterval = 200 - (speed - 1) * 25; // 速度范围1-8，对应间隔200ms-25ms
            
            // 更新最高分显示
            highScoreDisplay.textContent = highScore;
            
            // 初始化游戏
            function initGame() {
                // 初始化蛇，从网格中心开始
                const center = Math.floor(gridCount / 2);
                snake = [
                    { x: center, y: center },
                    { x: center - 1, y: center },
                    { x: center - 2, y: center }
                ];
                
                // 初始化方向和分数
                direction = 'right';
                nextDirection = 'right';
                score = 0;
                scoreDisplay.textContent = score;
                
                // 生成第一个食物
                generateFood();
                
                // 绘制游戏
                draw();
            }
            
            // 生成食物
            function generateFood() {
                // 随机位置
                const getRandomPosition = () => {
                    return {
                        x: Math.floor(Math.random() * gridCount),
                        y: Math.floor(Math.random() * gridCount)
                    };
                };
                
                // 确保食物不会出现在蛇身上
                let newFood;
                do {
                    newFood = getRandomPosition();
                } while (snake.some(segment => segment.x === newFood.x && segment.y === newFood.y));
                
                food = newFood;
            }
            
            // 移动蛇
            function moveSnake() {
                // 获取蛇头
                const head = { ...snake[0] };
                
                // 根据方向移动
                switch(direction) {
                    case 'up':
                        head.y -= 1;
                        break;
                    case 'down':
                        head.y += 1;
                        break;
                    case 'left':
                        head.x -= 1;
                        break;
                    case 'right':
                        head.x += 1;
                        break;
                }
                
                // 检查是否吃到食物
                if (head.x === food.x && head.y === food.y) {
                    // 增加分数
                    score += 10;
                    scoreDisplay.textContent = score;
                    
                    // 更新最高分
                    if (score > highScore) {
                        highScore = score;
                        highScoreDisplay.textContent = highScore;
                        localStorage.setItem('snakeHighScore', highScore);
                    }
                    
                    // 生成新食物
                    generateFood();
                } else {
                    // 如果没吃到食物，移除尾部
                    snake.pop();
                }
                
                // 检查碰撞
                if (
                    head.x < 0 || 
                    head.x >= gridCount || 
                    head.y < 0 || 
                    head.y >= gridCount || 
                    snake.some(segment => segment.x === head.x && segment.y === head.y)
                ) {
                    gameOver();
                    return;
                }
                
                // 添加新头部
                snake.unshift(head);
                
                // 绘制游戏
                draw();
            }
            
            // 绘制游戏
            function draw() {
                // 清空画布
                ctx.fillStyle = '#121212';
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                
                // 绘制网格（可选）
                ctx.strokeStyle = '#212121';
                ctx.lineWidth = 0.5;
                for (let i = 0; i < gridCount; i++) {
                    // 水平线
                    ctx.beginPath();
                    ctx.moveTo(0, i * cellSize);
                    ctx.lineTo(canvas.width, i * cellSize);
                    ctx.stroke();
                    
                    // 垂直线
                    ctx.beginPath();
                    ctx.moveTo(i * cellSize, 0);
                    ctx.lineTo(i * cellSize, canvas.height);
                    ctx.stroke();
                }
                
                // 绘制蛇
                snake.forEach((segment, index) => {
                    // 蛇头
                    if (index === 0) {
                        ctx.fillStyle = '#4CAF50';
                        ctx.shadowBlur = 10;
                        ctx.shadowColor = 'rgba(76, 175, 80, 0.5)';
                        ctx.beginPath();
                        ctx.roundRect(
                            segment.x * cellSize + 2, 
                            segment.y * cellSize + 2, 
                            cellSize - 4, 
                            cellSize - 4,
                            5
                        );
                        ctx.fill();
                        ctx.shadowBlur = 0;
                        
                        // 眼睛
                        ctx.fillStyle = 'white';
                        const eyeSize = cellSize / 8;
                        const eyeOffset = cellSize / 4;
                        
                        let leftEyeX, leftEyeY, rightEyeX, rightEyeY;
                        
                        switch(direction) {
                            case 'up':
                                leftEyeX = segment.x * cellSize + cellSize / 4;
                                leftEyeY = segment.y * cellSize + cellSize / 4;
                                rightEyeX = segment.x * cellSize + cellSize * 3 / 4 - eyeSize;
                                rightEyeY = leftEyeY;
                                break;
                            case 'down':
                                leftEyeX = segment.x * cellSize + cellSize / 4;
                                leftEyeY = segment.y * cellSize + cellSize * 3 / 4 - eyeSize;
                                rightEyeX = segment.x * cellSize + cellSize * 3 / 4 - eyeSize;
                                rightEyeY = leftEyeY;
                                break;
                            case 'left':
                                leftEyeX = segment.x * cellSize + cellSize / 4;
                                leftEyeY = segment.y * cellSize + cellSize / 4;
                                rightEyeX = leftEyeX;
                                rightEyeY = segment.y * cellSize + cellSize * 3 / 4 - eyeSize;
                                break;
                            case 'right':
                                leftEyeX = segment.x * cellSize + cellSize * 3 / 4 - eyeSize;
                                leftEyeY = segment.y * cellSize + cellSize / 4;
                                rightEyeX = leftEyeX;
                                rightEyeY = segment.y * cellSize + cellSize * 3 / 4 - eyeSize;
                                break;
                        }
                        
                        ctx.beginPath();
                        ctx.arc(leftEyeX, leftEyeY, eyeSize, 0, Math.PI * 2);
                        ctx.arc(rightEyeX, rightEyeY, eyeSize, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 瞳孔
                        ctx.fillStyle = 'black';
                        ctx.beginPath();
                        ctx.arc(leftEyeX + eyeSize/2, leftEyeY, eyeSize/2, 0, Math.PI * 2);
                        ctx.arc(rightEyeX + eyeSize/2, rightEyeY, eyeSize/2, 0, Math.PI * 2);
                        ctx.fill();
                    } 
                    // 蛇身体
                    else {
                        // 根据位置设置颜色渐变
                        const greenValue = 175 - (index % 10) * 15;
                        ctx.fillStyle = `rgb(76, ${greenValue}, 80)`;
                        
                        // 绘制圆角矩形身体
                        ctx.beginPath();
                        ctx.roundRect(
                            segment.x * cellSize + 2, 
                            segment.y * cellSize + 2, 
                            cellSize - 4, 
                            cellSize - 4,
                            3
                        );
                        ctx.fill();
                        
                        // 绘制身体花纹
                        ctx.fillStyle = 'rgba(255, 255, 255, 0.1)';
                        ctx.beginPath();
                        ctx.arc(
                            segment.x * cellSize + cellSize / 2,
                            segment.y * cellSize + cellSize / 2,
                            cellSize / 6,
                            0,
                            Math.PI * 2
                        );
                        ctx.fill();
                    }
                });
                
                // 绘制食物
                ctx.fillStyle = '#FF5722';
                ctx.shadowBlur = 15;
                ctx.shadowColor = 'rgba(255, 87, 34, 0.7)';
                ctx.beginPath();
                ctx.arc(
                    food.x * cellSize + cellSize / 2,
                    food.y * cellSize + cellSize / 2,
                    cellSize / 2 - 2,
                    0,
                    Math.PI * 2
                );
                ctx.fill();
                ctx.shadowBlur = 0;
                
                // 绘制光泽效果
                ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
                ctx.beginPath();
                ctx.arc(
                    food.x * cellSize + cellSize * 0.7,
                    food.y * cellSize + cellSize * 0.3,
                    cellSize / 6,
                    0,
                    Math.PI * 2
                );
                ctx.fill();
            }
            
            // 开始游戏
            function startGame() {
                if (gameState === 'ready' || gameState === 'gameOver' || gameState === 'paused') {
                    gameState = 'running';
                    startScreen.classList.add('hidden');
                    gameOverScreen.classList.add('hidden');
                    pauseButton.innerHTML = '<i class="fa fa-pause mr-2"></i>暂停游戏';
                    
                    gameLoop = (currentTime) => {
                        if (!lastTime) lastTime = currentTime;
                        const deltaTime = currentTime - lastTime;
                        
                        if (deltaTime > speedInterval) {
                            lastTime = currentTime;
                            direction = nextDirection;
                            moveSnake();
                        }
                        
                        if (gameState === 'running') {
                            requestAnimationFrame(gameLoop);
                        }
                    };
                    
                    let lastTime = 0;
                    requestAnimationFrame(gameLoop);
                }
            }
            
            // 暂停游戏
            function pauseGame() {
                if (gameState === 'running') {
                    gameState = 'paused';
                    pauseButton.innerHTML = '<i class="fa fa-play mr-2"></i>继续游戏';
                } else if (gameState === 'paused') {
                    startGame();
                }
            }
            
            // 游戏结束
            function gameOver() {
                gameState = 'gameOver';
                finalScore.textContent = score;
                gameOverScreen.classList.remove('hidden');
            }
            
            // 键盘控制
            document.addEventListener('keydown', (e) => {
                // 防止方向键滚动页面
                if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'w', 's', 'a', 'd', 'W', 'S', 'A', 'D'].includes(e.key)) {
                    e.preventDefault();
                }
                
                // 开始/暂停游戏
                if (e.key === ' ' || e.key === 'Spacebar') {
                    if (gameState === 'ready') {
                        startGame();
                    } else if (gameState === 'running' || gameState === 'paused') {
                        pauseGame();
                    }
                    return;
                }
                
                // 游戏未开始或已结束时不响应方向键
                if (gameState !== 'running' && gameState !== 'paused') {
                    return;
                }
                
                // 方向控制
                switch(e.key) {
                    case 'ArrowUp':
                    case 'w':
                    case 'W':
                        if (direction !== 'down') {
                            nextDirection = 'up';
                            console.log('Direction changed to up'); // 调试日志
                        }
                        break;
                    case 'ArrowDown':
                    case 's':
                    case 'S':
                        if (direction !== 'up') {
                            nextDirection = 'down';
                            console.log('Direction changed to down'); // 调试日志
                        }
                        break;
                    case 'ArrowLeft':
                    case 'a':
                    case 'A':
                        if (direction !== 'right') {
                            nextDirection = 'left';
                            console.log('Direction changed to left'); // 调试日志
                        }
                        break;
                    case 'ArrowRight':
                    case 'd':
                    case 'D':
                        if (direction !== 'left') {
                            nextDirection = 'right';
                            console.log('Direction changed to right'); // 调试日志
                        }
                        break;
                }
            });
            
            // 触摸控制
            directionButtons.forEach(button => {
                button.addEventListener('click', () => {
                    const newDirection = button.dataset.direction;
                    
                    // 防止180度转向
                    if (
                        (newDirection === 'up' && direction !== 'down') ||
                        (newDirection === 'down' && direction !== 'up') ||
                        (newDirection === 'left' && direction !== 'right') ||
                        (newDirection === 'right' && direction !== 'left')
                    ) {
                        nextDirection = newDirection;
                    }
                    
                    // 如果游戏暂停，点击方向键开始游戏
                    if (gameState === 'paused') {
                        startGame();
                    }
                });
            });
            
            // 速度控制
            speedSlider.addEventListener('input', () => {
                speed = parseInt(speedSlider.value);
                speedValue.textContent = speed;
                speedInterval = 200 - (speed - 1) * 25; // 速度范围1-8，对应间隔200ms-25ms
            });
            
            // 按钮事件
            startButton.addEventListener('click', startGame);
            restartButton.addEventListener('click', () => {
                initGame();
                startGame();
            });
            pauseButton.addEventListener('click', pauseGame);
            
            // 初始化游戏
            initGame();
        });
    </script>
</body>
</html>
    